package com.local.web.advice;

import com.local.cart.pojo.ShoppingCart;
import com.local.user.pojo.User;
import com.local.web.constants.CaptchaTypeEnum;
import com.local.web.constants.WebConstants;
import com.local.web.service.ShoppingCartService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Arrays;
import java.util.List;

/**
 * 声明切面处理类
 */

@Component
@Aspect
public class LoginAdvice {

    @Autowired
    private ShoppingCartService shoppingCartService;


    /**
     * 声明切入方法：用户登录后，把购物车数据从db保存至redis
     * @param proceedingJoinPoint
     */
    @Around("execution(public com.local.user.pojo.User com.local.web.service.UserService.getByLoginNamePassword(..))")
    public User saveShoppingToRedis(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object[] args = proceedingJoinPoint.getArgs();
        HttpSession session = (HttpSession) args[1];
        User userResult = (User) proceedingJoinPoint.proceed();//{userId=16, nickName='130189298400', loginName='13018929840', passwordMd5='e10adc3949ba59abbe56e057f20f883e', introduceSign='我的个性签名', address='澳华新村1200，13018929840，老曾', isDeleted=0, lockedFlag=0, createTime='2022-10-26 15:43:40', shopCartItemCount='null'}

        //移除session中的登录验证码
        session.removeAttribute(CaptchaTypeEnum.LOGIN_CAPTCHA.getValue());
        //将登录用户信息保存到session
        userResult.setShopCartItemCount(0);
        session.setAttribute(WebConstants.WEB_USER_SESSION_KEY, userResult);
        //查询购物车数据，并保存到session
        shoppingCartService.getListByUserId(session, userResult.getUserId());

        return userResult;
    }
}
